'use strict';
app.controller('reportCtrl', ["$scope","$rootScope", "$state", "$timeout", "$interval", "$http", "$cookieStore", "moment", "SweetAlert", "Restangular", "api_report", "api_statistic", function ($scope, $rootScope, $state, $timeout, $interval, $http, $cookieStore, moment, SweetAlert, Restangular, api_report, api_statistic) {
	var ROWS = "ROWS";
	var COLUMNS = "COLUMNS";
    $scope.treeshow=true;
    $scope.headers = "请选择事件树形列表！";
	api_report.getLicenseKey().then(function(response){
		$cookieStore.put('Auth-Token',response.token);
		$scope.try_async_load();
	});
	var apple_selected, tree, treedata_avm, treedata_geography;
	var workspace = {};
	$scope.parameters = {};
	$scope.reportName = "ITSM报表";
	$scope.allheight=100;
  	$scope.my_tree_handler = function (branch) {
        $scope.treeshow=false;
  		
  		if(branch.type=='FILE'){
  			console.log(branch);
  			$scope.reportName=branch.label;
  			var path=$scope.mdxpath=branch.path;
  			queryUUID=genUUID();
	        api_report.getMdx(path,queryUUID).then(function(response){
	            var mdxquery = Restangular.stripRestangular(response);
	            workspace.query = mdxquery;
                var starttime,endtime
                starttime=moment().startOf('week').format('YYYYMMDD');
                endtime=moment().endOf('week').format('YYYYMMDD');


                var year=new Date().getFullYear();
                    var month=new Date().getMonth()+1;
                    var day=new Date().getDate();
                    var days=0;
                    for(var i=0;i<month;i++){
                        switch(i){
                            case 1:{
                                days+=31;break;
                            }
                            case 3:{
                                days+=31;break;
                            }
                            case 5:{
                                days+=31;break;
                            }
                            case 7:{
                                days+=31;break;
                            }
                            case 8:{
                                days+=31;break;
                            }
                            case 10:{
                                days+=31;break;
                            }
                            case 12:{
                                days+=31;break;
                            }
                            case 4:{
                                days+=30;break;
                            }
                            case 6:{
                                days+=30;break;
                            }
                            case 9:{
                                days+=30;break;
                            }
                            case 11:{
                                days+=30;break;
                            }
                            case 2:{
                                if((year%4==0&&year%100!=0)||(year%400==0)){
                                    days+=29
                            }else{days+=28}
                            break;
                        }
                    }
                }
                days+=day;
                // var dayss＝'';
                var date0=new Date(year,0,1);
                var oneDayWeek=date0.getDay()==0?7:date0.getDay();
                var oneWeekDay=7-oneDayWeek+1;
                var shengdays=days-oneWeekDay;
                var nthOfWeek=Math.ceil(shengdays/7)+1;
                var weeks=shengdays%7;
                // if(day){}
                var dayss=day-weeks+1-6;
                var dayl=day-weeks;
                var month1=month;
                var month2=month;
                var year1=year;
                var year2=year;
                        switch(month){
                            case 1:{
                                if((day-weeks+1-6)<=0){dayss=25+day-weeks;month1=month-1}else{
                                    if(dayss>31){dayss=dayss-31;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+31-weeks;month2=month-1;}else{
                                    if(dayl>31){dayl=dayl-31;month2=month+1;}
                                }
                                break;
                            }
                            case 3:{
                                if((year%4==0&&year%100!=0)||(year%400==0)){
                                    if((day-weeks+1-6)<=0){dayss=23+day-weeks;month1=month-1}else{
                                        if(dayss>31){dayss=dayss-31;month1=month+1;}}
                                    if((day-weeks)<=0){dayl=day+29-weeks;month2=month-1;}else{
                                        if(dayl>31){dayl=dayl-31;month2=month+1;}
                                    }
                                }else{
                                    if((day-weeks+1-6)<=0){dayss=22+day-weeks;month1=month-1}else{
                                        if(dayss>31){dayss=dayss-31;month1=month+1;}}
                                    if((day-weeks)<=0){dayl=day+28-weeks;month2=month-1;}else{
                                        if(dayl>31){dayl=dayl-31;month2=month+1;}
                                    }
                                }

                                break;
                            }
                            case 5:{
                                if((day-weeks+1-6)<=0){dayss=24+day-weeks;month1=month-1}else{
                                    if(dayss>31){dayss=dayss-31;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+30-weeks;month2=month-1;}else{
                                    if(dayl>31){dayl=dayl-31;month2=month+1;}
                                }
                                break;
                            }
                            case 7:{
                                if((day-weeks+1-6)<=0){dayss=24+day-weeks;month1=month-1}else{
                                    if(dayss>31){dayss=dayss-31;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+30-weeks;month2=month-1;}else{
                                    if(dayl>31){dayl=dayl-31;month2=month+1;}
                                }
                                break;
                            }
                            case 8:{
                                if((day-weeks+1-6)<=0){dayss=25+day-weeks;month1=month-1}else{
                                    if(dayss>31){dayss=dayss-31;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+31-weeks;month2=month-1;}else{
                                    if(dayl>31){dayl=dayl-31;month2=month+1;}
                                }
                                break;
                            }
                            case 10:{
                                if((day-weeks+1-6)<=0){dayss=24+day-weeks;month1=month-1}else{
                                    if(dayss>31){dayss=dayss-31;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+30-weeks;month2=month-1;}else{
                                    if(dayl>31){dayl=dayl-31;month2=month+1;}
                                }
                                break;
                            }
                            case 12:{
                                if((day-weeks+1-6)<=0){dayss=24+day-weeks;month1=month-1}else{
                                    if(dayss>31){dayss=dayss-31;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+30-weeks;month2=month-1;}else{
                                    if(dayl>31){dayl=dayl-31;month2=month+1;}
                                }
                                break;
                                // if(dayss>31){dayss=dayss-30;
                                // month1=month+1;if(month>12){month1=month-12;year1=year+1}}
                                // if(dayl>31){dayl=dayl-31;
                                // month2=month+1;if(month>12){month2=month-12;year2=year+1}}
                                // break;
                            }
                            case 4:{
                                if((day-weeks+1-6)<=0){dayss=25+day-weeks;month1=month-1}else{
                                    if(dayss>30){dayss=dayss-30;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+31-weeks;month2=month-1;}else{
                                    if(dayl>30){dayl=dayl-30;month2=month+1;}
                                }
                                break;
                            }
                            case 6:{
                                if((day-weeks+1-6)<=0){dayss=25+day-weeks;month1=month-1}else{
                                    if(dayss>30){dayss=dayss-30;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+31-weeks;month2=month-1;}else{
                                    if(dayl>30){dayl=dayl-30;month2=month+1;}
                                }
                                break;
                            }
                            case 9:{
                                if((day-weeks+1-6)<=0){dayss=25+day-weeks;month1=month-1}else{
                                    if(dayss>30){dayss=dayss-30;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+31-weeks;month2=month-1;}else{
                                    if(dayl>30){dayl=dayl-30;month2=month+1;}
                                }
                                break;

                                // if(dayss>30){dayss=dayss-31;month1=month+1;}
                                // if(dayl>30){dayl=dayl-30;month2=month+1;}
                                // break;
                            }
                            case 11:{
                                if((day-weeks+1-6)<=0){dayss=25+day-weeks;month1=month-1}else{
                                    if(dayss>30){dayss=dayss-30;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+31-weeks;month2=month-1;}else{
                                    if(dayl>30){dayl=dayl-30;month2=month+1;}
                                }
                                break;
                            }
                            case 2:{

                                    if((year%4==0&&year%100!=0)||(year%400==0)){
                                        if((day-weeks+1-6)<=0){dayss=25+day-weeks;month1=month-1}else{
                                    if(dayss>29){dayss=dayss-29;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+31-weeks;month2=month-1;}else{
                                    if(dayl>29){dayl=dayl-29;month2=month+1;}
                                }
                                break;
                                    //     if(dayss>29){dayss=dayss-31;month1=month+1;}
                                    //     if(dayl>29){dayl=dayl-29;month2=month+1;}
                                    // break;
                                    }else{
                                        if((day-weeks+1-6)<=0){dayss=25+day-weeks;month1=month-1}else{
                                    if(dayss>28){dayss=dayss-28;month1=month+1;}}
                                if((day-weeks)<=0){dayl=day+31-weeks;month2=month-1;}else{
                                    if(dayl>28){dayl=dayl-28;month2=month+1;}
                                }
                                break;
                                        // if(dayss>28){dayss=dayss-31;month1=month+1;}
                                        // if(dayl>28){dayl=dayl-28;month2=month+1;}
                                        // break;
                                    }
                            break;
                        }
                    } 
                    var mom1=month1.toString();
                    var mom2=month2.toString();
                    var da1=dayss.toString();
                    var da2=dayl.toString();
                    if(month1.toString().length<2){mom1="0"+month1.toString()};
                    if(month2.toString().length<2){mom2="0"+month2.toString()};
                    if(dayss.toString().length<2){da1="0"+dayss.toString()}
                    if(dayl.toString().length<2){da2="0"+dayl.toString()}
                    workspace.query.parameters.paramDateFrom=year.toString()+mom1+da1;
                    workspace.query.parameters.paramDateTo=year.toString()+mom2+da2;
                    $scope.parameters = parseDateParameter(workspace.query.parameters);
                    $scope.disabledParentGroup=false;
                    $scope.shows=false;
	            if(workspace.query.parameters.reportUUID){
	            	
	            	$scope.rptUUID = workspace.query.parameters.reportUUID;
	            	delete workspace.query.parameters.reportUUID;
	            	$scope.parameters = parseDateParameter(workspace.query.parameters);
	            	api_statistic.query(workspace.query.parameters,$scope.rptUUID).then(function(data){
	            			$scope.rheaders = [];
		    						$scope.rRows = [];
	            			var reportData = Restangular.stripRestangular(data);
                            if(reportData.cellset.length<2){
                                  reportData.cellset=null;
                                  $scope.shows=true;$scope.empty="数据为空！"
                            }
	            			var tableContent = render(reportData);
	            	})
	            	
	            }else{
	            	$scope.rptUUID = undefined;
	            	
	            	api_report.execute(mdxquery).then(function(data){
			            	$scope.rheaders = [];
		    						$scope.rRows = [];
			            	var reportData = Restangular.stripRestangular(data);
                            if($scope.reportName=="事件工作回顾"&&reportData.cellset.length<4){
                                  reportData.cellset=null;
                            }
                            if($scope.reportName=="事件解决率统计"&&reportData.cellset.length<4){
                                  reportData.cellset=null;
                            }
                            if(reportData.cellset==null||reportData.cellset.length==0){$scope.shows=true;$scope.empty="数据为空！"}
			            	//console.log(reportData);
			            	var tableContent = render(reportData);
			            	renderChart(reportData);
			            	//console.log(tableContent);
			            	//console.log($scope.rheaders);
			          })    
	            }
	            
	            //http://localhost:9008/api/statistic/unidimensional/d75e22c1-7f60-4e22-affd-23742a475407          
	        });
  		}
  	}

    $scope.my_data = [];

  	$scope.my_tree = tree = {};
    $scope.try_async_load = function () {
        $scope.my_data = [];
        $scope.select_treedata = [];
        api_report.list().then(function(response){
			var dataList = Restangular.stripRestangular(response);
			getRepoRoot(dataList, '/homes/home:admin/ITSM报表');

			convertRepoObject($scope.repoRoot);
			
			$scope.my_data.push($scope.repoRoot);

		});
    };
    $scope.repoRoot = null;
    function getRepoRoot(repo, path){
    	angular.forEach(repo, function(value, key){
    		if(value.path==path){
    			$scope.repoRoot=value;
    		}else{
    			if($scope.repoRoot==null&&angular.isDefined(value.repoObjects)){
    				getRepoRoot(value.repoObjects, path);
    			}else{

    			}    			
    		}
    	});
    }

    function convertRepoObject(repo) {
    	if(angular.isArray(repo)){
    		angular.forEach(repo, function(value, key){
    			convertRepoObject(value);
    		})
    	}else{
    		if(angular.isDefined(repo.name)){
	        	if(repo.name.indexOf(".")>=0){
	        		repo.label = repo.name.substr(0, repo.name.lastIndexOf("."));
	        	}else{
	        		repo.label = repo.name;
	        	}
	        	//delete repo.name;
	        }
    		if(angular.isDefined(repo.repoObjects)){
	        	repo.children = [];
	        	repo.children = repo.repoObjects;
	        	delete repo.repoObjects;
	        	convertRepoObject(repo.children);
	        }
	        
    	}
    } 

    function convertListToTree(data, treeMap){
        var idToNodeMap = {}; //Keeps track of nodes using id as key, for fast lookup
        var root = null; //Initially set our loop to null
        var parentNode = null;
        //loop over data
        for(var i = 0; i < data.length; i++) {
            var datum = data[i];
            //each node will have children, so let's give it a "children" poperty
            datum.children = [];

            //add an entry for this node to the map so that any future children can
            //lookup the parent
            idToNodeMap[datum.id] = datum;

            //Does this node have a parent?
            if(typeof datum.parent === "undefined" || datum.parent == null) {
                //Doesn't look like it, so this node is the root of the tree
                root = datum;
                treeMap[datum.id] = root;
            } else {        
                //This node has a parent, so let's look it up using the id
                parentNode = idToNodeMap[datum.parent.id];

                //We don't need this property, so let's delete it.
                delete datum.parent;

                //Let's add the current node as a child of the parent node.
                parentNode.children.push(datum);        
            }
        }
        return root;
    }

    function convertParentToChildList(data){
        var treeMap = {};
        var list=[];
        convertListToTree(data, treeMap);
        angular.forEach(treeMap,function(item){
            list.push(item);
        });
        return list;
    }

    function parseDateParameter(parameters){
    	var result=undefined;
    	if(angular.isArray(parameters)){
    		// angular.forEach(parmeters,function(param){
    		// 	param.
    		// })
    	}else{
    		result = {};
    		for(var k in parameters){
    			if(k.indexOf("Date")>0){
    				if(angular.isString(parameters[k])){
    					result[k] = moment(parameters[k], "YYYYMMDD").format("YYYY-MM-DD");
    					//result[k] = ''+parameters[k]+'';//= moment(parameters[k], "YYYYMMDD").toDate();
    				}
    			}
    		}
    	}
    	return result;
    }

    function ConvertDateParameter(parameters){
    	var result=undefined;
    	if(angular.isArray(parameters)){
    		// 
    	}else{
    		result={};
    		for(var k in parameters){
    			if(k.indexOf("Date")>0){
    				if(angular.isDate(parameters[k])){
    					result[k]=moment(parameters[k]).format("YYYYMMDD");
    				}else if(angular.isString(parameters[k])){
    					result[k]=parameters[k];
    				}
    			}
    		}
    	}
    	return result;
    }

    $scope.open = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();

        $scope.opened = !$scope.opened;
    };
    $scope.endOpen = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.startOpened = false;
        $scope.endOpened = !$scope.endOpened;
    };
    $scope.startOpen = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.endOpened = false;
        $scope.startOpened = !$scope.startOpened;
    };

    $scope.mdxquery = function () {
        $scope.shows=false;
    	if(angular.isDefined(workspace.query)){
    		if($scope.rptUUID){  	
          	workspace.query.parameters=ConvertDateParameter($scope.parameters);
            workspace.query.parameters.paramDateFrom=workspace.query.parameters.paramDateFrom.replace(/-/g,"");
            workspace.query.parameters.paramDateTo=workspace.query.parameters.paramDateTo.replace(/-/g,"");
          	api_statistic.query(workspace.query.parameters,$scope.rptUUID).then(function(data){
          			$scope.rheaders = [];
    						$scope.rRows = [];
          			var reportData = Restangular.stripRestangular(data);
                    if(reportData.cellset.length<2){
                          reportData.cellset=null;
                          $scope.shows=true;$scope.empty="数据为空！"
                    }
          			var tableContent = render(reportData);
          	})
          	
        }else{
        	$scope.rptUUID = undefined;
        	workspace.query.parameters=ConvertDateParameter($scope.parameters);
        	if(angular.isDefined($scope.parameters.paramDateFrom)&&angular.isDefined($scope.parameters.paramDateTo)){
        		workspace.query.parameters.paramDateFrom=workspace.query.parameters.paramDateFrom.replace(/-/g,"");
        		workspace.query.parameters.paramDateTo=workspace.query.parameters.paramDateTo.replace(/-/g,"");
        	    // workspace.query.parameters=ConvertDateParameter($scope.parameters);
	    		api_report.execute(workspace.query).then(function(data){
                   console.log($scope.reportName)
		        	$scope.rheaders = [];
							$scope.rRows = [];
		        	var reportData = Restangular.stripRestangular(data);
                   if($scope.reportName=="事件工作回顾"&&reportData.cellset.length<4){
                          reportData.cellset=null;
                    }
                    if($scope.reportName=="事件解决率统计"&&reportData.cellset.length<4){
                          reportData.cellset=null;
                    }
                    if(reportData.cellset==null||reportData.cellset.length==0){$scope.shows=true;$scope.empty="数据为空！"}
		        	console.log(reportData);
		        	var tableContent =
		        	 render(reportData);
		        	renderChart(reportData);	        	
		        	console.log($scope.rheaders);
		        }) 
		        }  
        }
    	}
		 
    }

    $scope.execute = function () {
    	api_report.list($scope.token).then(function(response){
			$scope.select_treedata = $scope.my_data = response;
		});
    }

    $scope.searchOptions = function(){
    	if(angular.isDefined(workspace.query)){
    		var queryParameters = workspace.query.parameters;
	    	for(var parm in queryParameters){
	    		if(parm=='Week'){

	    		}else{

	    		}
	    	}
    	}
    }
    



    $scope.activeParentGroup = false;
    $scope.disabledParentGroup = false;
    $scope.toggleParentGroup = function(){
    	if(workspace.query){
    		// if($scope.activeParentGroup){
    			// workspace.query.properties['saiku.olap.result.formatter']='flat';
    			// $scope.activeParentGroup=!$scope.activeParentGroup;
    		// }else{
    			workspace.query.properties['saiku.olap.result.formatter']='flattened';
    			// $scope.activeParentGroup=!$scope.activeParentGroup;
    		// }
    		//console.log(workspace.query);
    		executeQuery(workspace.query);
    	}   	
    }


    var process_data_tree = function (args, flat, setdata) {
	    var self = this;
	    var data = {};
	    if (flat) {
	        data.resultset = [];
	        data.metadata = [];
	        data.height = 0;
	        data.width = 0;
	    }

	    var currentDataPos = data;
	    if (typeof args == "undefined" || typeof args.data == "undefined") {
	        return;
	    }

	    if (args.data !== null && args.data.error !== null) {
	        return;
	    }
	    // Check to see if there is data
	    if (args.data === null || (args.data.cellset && args.data.cellset.length === 0)) {
	        return;
    	}

	    var cellset = args.data.cellset;
	    if (cellset && cellset.length > 0) {
	        var lowest_level = 0;
	        var data_start = 0;
	        var hasStart = false;
	        var row,
	            rowLen,
	            labelCol,
	            reduceFunction = function (memo, num) {
	                return memo + num;
	            };

	        for (row = 0, rowLen = cellset.length; data_start === 0 && row < rowLen; row++) {
	            for (var field = 0, fieldLen = cellset[row].length; field < fieldLen; field++) {
	                if (!hasStart) {
	                    while (cellset[row][field].type == "COLUMN_HEADER" && cellset[row][field].value == "null") {
	                        row++;
	                    }
	                }
	                hasStart = true;
	                if (cellset[row][field].type == "ROW_HEADER_HEADER") {
	                    while (cellset[row][field].type == "ROW_HEADER_HEADER") {
	                        if (flat) {
	                            data.metadata.push({
	                                colIndex: field,
	                                colType: "String",
	                                colName: cellset[row][field].value
	                            });
	                        }
	                        field++;
	                    }
	                    lowest_level = field - 1;
	                }
	                if (cellset[row][field].type == "COLUMN_HEADER") {
	                    var lowest_col_header = 0;
	                    var colheader = [];
	                    while (lowest_col_header <= row) {
	                        if (cellset[lowest_col_header][field].value !== "null") {
	                            colheader.push(cellset[lowest_col_header][field].value);
	                        }
	                        lowest_col_header++;
	                    }
	                    if (flat) {
	                        data.metadata.push({
	                            colIndex: field,
	                            colType: "Numeric",
	                            colName: colheader.join(' ~ ')
	                        });
	                    }
	                    data_start = row + 1;
	                }
	            }
	        }
	        var labelsSet = {};
	        var rowlabels = [];
	        for (labelCol = 0; labelCol <= lowest_level; labelCol++) {
	            rowlabels.push(null);
	        }
	        for (row = data_start, rowLen = cellset.length; row < rowLen; row++) {
	            if (cellset[row][0].value !== "") {
	                var record = [];
	                var flatrecord = [];
	                var parent = null;
	                var rv = null;

	                for (labelCol = 0; labelCol <= lowest_level; labelCol++) {
	                    if (cellset[row] && cellset[row][labelCol].value === 'null') {
	                        currentDataPos = data;
	                        var prevLabel = 0;
	                        for (; prevLabel < lowest_level && cellset[row][prevLabel].value === 'null'; prevLabel++) {
	                            currentDataPos = currentDataPos[rowlabels[prevLabel]];
	                        }
	                        if (prevLabel > labelCol) {
	                            labelCol = prevLabel;
	                        }

	                    }
	                    if (cellset[row] && cellset[row][labelCol].value !== 'null') {
	                        if (labelCol === 0) {
	                            for (var xx = 0; xx <= lowest_level; xx++) {
	                                rowlabels[xx] = null;
	                            }
	                        }
	                        if (typeof currentDataPos == "number") {
	                            parent[rv] = {};
	                            currentDataPos = parent[rv];
	                        }
	                        rv = cellset[row][labelCol].value;
	                        rowlabels[labelCol] = rv;

	                        if (!currentDataPos.hasOwnProperty(rv)) {
	                            currentDataPos[rv] = {};
	                        }
	                        parent = currentDataPos;
	                        currentDataPos = currentDataPos[rv];
	                    }
	                }
	                flatrecord = _.clone(rowlabels);
	                for (var col = lowest_level + 1, colLen = cellset[row].length; col < colLen; col++) {
	                    var cell = cellset[row][col];
	                    var value = cell.value || 0;
	                    var maybePercentage = (value !== 0);
	                    // check if the resultset contains the raw value, if not try to parse the given value
	                    var raw = cell.properties.raw;
	                    if (raw && raw !== "null") {
	                        value = parseFloat(raw);
	                    } else if (typeof(cell.value) !== "number" && parseFloat(cell.value.replace(/[^a-zA-Z 0-9.]+/g, ''))) {
	                        value = parseFloat(cell.value.replace(/[^a-zA-Z 0-9.]+/g, ''));
	                        maybePercentage = false;
	                    }
	                    if (value > 0 && maybePercentage) {
	                        value = cell.value && cell.value.indexOf('%') >= 0 ? value * 100 : value;
	                    }
	                    record.push(value);

	                    flatrecord.push({f: cell.value, v: value});
	                }
	                if (flat) data.resultset.push(flatrecord);
	                var sum = _.reduce(record, reduceFunction, 0);
	                rv = (rv === null ? "null" : rv);
	                parent[rv] = sum;
	                currentDataPos = data;
	            }
	        }
	        if (setdata) {
	            self.rawdata = args.data;
	            self.data = data;
	            self.hasProcessed = true;
	            self.data.height = self.data.resultset.length;
	        }
	        return data;
	    } else {
	        //no result
	        //$(self.el).find('.canvas_wrapper').text("No results").show();
	    }
	};





	// function randColor() {
 //        tmpHSV=randomHSV(tmpHSV);
 //        return colorToHex(HSVToRGB(tmpHSV.h,tmpHSV.s, tmpHSV.v));
 //        // console.log()
 //    };

 //    function highlightColor(){
 //    	var highlight = {
 //    		h:tmpHSV.h+5.5,
	// 		s:0.55,
	// 		v:0.5
 //    	};
 //    	return colorToHex(HSVToRGB(highlight.h,highlight.s, highlight.v));
 //    }
 


    var renderChart = function(reportData){
    	var data = process_data_tree({data:reportData});
    	var _ = window._;
    	var dataChart = undefined;
    	$scope.chartData = [];
		// tmpHSV=undefined;
    	if(workspace.query){
    			if(workspace.query.properties['saiku.ui.render.type']=="sunburst"){
    				$scope.chartType="pie";
    				dataChart = [];
    				var total=0;
                    var i=0;
    				_.forIn(data, function(value, key) {
    					  total+=value;
                          i++;
						  dataChart.push({
						  	label:key,
						  	value:value,
						  	color:randColor()
						  });

					});
                    function randColor(){
                            if(i%4==1){return '#01A2D9'}
                            else  if(i%4==2){return '#71BBDE'}
                            else if(i%4==3){return '#FF9122'}
                            else if(i%4==0){return '#F8B705'}
                        }
					console.log(total);
                    // for(var i=0;i<dataChart.length;i++){
                    //     dataChart[i].value=dataChart[i].value*100/total
                    //     dataChart[i].value=dataChart[i].value.toFixed(2);
                    // }
    				$scope.chartData = dataChart;
					$scope.chartOptions = {
					  // responsive: true,
				   //    //Boolean - Whether we should show a stroke on each segment
				       segmentShowStroke : true,
				   //    //String - The colour of each segment stroke
				   //    segmentStrokeColor : '#fff',
				   //    //Number - The width of each segment stroke
				       segmentStrokeWidth : 2,
				   //    //Number - The percentage of the chart that we cut out of the middle
				   //    percentageInnerCutout : 0, // This is 0 for Pie charts
				   //    //Number - Amount of animation steps
				   //    animationSteps : 100,
				   //    //String - Animation easing effect
				   //    animationEasing : 'easeOutBounce',
				   //    //Boolean - Whether we animate the rotation of the Doughnut
				   //    animateRotate : true,
				   //    //Boolean - Whether we animate scaling the Doughnut from the centre
				   //    animateScale : false,
				   //    //String - A legend template
				       legendTemplate : '<ul class="tc-chart-js-legend col-md-2.5 " style="float:right;margin-top:-250px;z-index: 999;"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>',
				       //showTooltips:false,
				       //tooltipEvents:[],
				       onAnimationComplete: function(){
				       		//this.showTooltip(this.segments, true);
				       		//console.log(this.segments)
				       }

					};
    			}else if(workspace.query.properties['saiku.ui.render.type']=="stackedBar"){
    				$scope.chartType="bar";
    				dataChart = {};
    				var labels=[];
    				var barData =[];
    				_.forIn(data, function(value, key) {
    					labels.push(key);
						barData.push(value);
					});
					dataChart={
						labels:labels,
						datasets:[]
					};
					dataChart.datasets.push({
						//label:'事件数',
						fillColor: '#0E7EC5',
						strokeColor: 'rgba(220,220,220,0.8)',
						highlightFill: 'rgba(220,220,220,0.75)',
						highlightStroke: 'rgba(220,220,220,1)',
						data:barData
					});
    				$scope.chartData = dataChart;
    				$scope.chartOptions = {};
    			}
    			//"line"
    			//"bar"
    			//"radar"
    			//"polararea"
    			//"pie"
    			//"doughnut"
    	}   
    }

    var queryUUID;
    function genUUID(){
    	var uuid = 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
            function (c) {
                var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            }).toUpperCase();
    	return uuid;
    }

    function exportMdxBefore(path,uuid, callback){
    	var rdata = 'file='+path+'&formatter=flattened&language=zh';
    	$http({
    			url: api_report.queryMdxUri(uuid).getRequestedUrl(),
    			method: 'POST',
    			data: rdata,
    			headers: {
    				'Content-Type': 'application/x-www-form-urlencoded',
    				'X-Auth-Token' : $cookieStore.get('Auth-Token')||null
    			}
    		}).success(function(data, status, headers, config) {
    			if(status==200){
    				if(callback){
    					callback(data.name, path);
    				}
    			}
    			//console.log(status);
    			//console.log(data);
    		});
    }

	$scope.exportData = function(uuid){
		//var url=api_report.exportData($scope.mdxpath).getRequestedUrl();


		if(!uuid&&queryUUID){
			uuid=queryUUID;
		}

		var name = $scope.mdxpath;
		// if(workspace.query.name!=undefined){
		// 	exportMdxBefore(name,uuid, function(queryName,path){
		// 		var filename = path.substring(path.lastIndexOf('/')+1).slice(0, -5);
		// 		$http({
  //                   url : api_report.exportData('flat', queryName, encodeURIComponent(filename)).getRequestedUrl(),
  //                   method : 'GET',
  //                   params : {},
  //                   headers : {
  //                       //'Content-type' : 'application/xls',
  //                       'Accept': 'application/vnd.ms-excel',
  //                       'X-Auth-Token' : $cookieStore.get('Auth-Token')||null
  //                   },
  //                   responseType : 'arraybuffer'
  //               }).success(function(data, status, headers, config) {
  //                       var file = new Blob([ data ], {
  //                           type : 'application/vnd.ms-excel'
  //                       });
  //                       //trick to download store a file having its URL
  //                       var fileURL = URL.createObjectURL(file);
  //                       var a         = document.createElement('a');
  //                       a.href        = fileURL; 
  //                       a.target      = '_blank';
  //                       a.download    = filename+"xls";
  //                       document.body.appendChild(a);
  //                       a.click();
  //               }).error(function(data, status, headers, config) {
  //                   console.log(data);
  //               });
		// 	});
		// }

		// return;
		//return url;
        if(workspace.query.name!=undefined){
            var filename = name.substring(name.lastIndexOf('/')+1).slice(0, -5);
            if(filename=="事件详细资料."){
                // api_statistic.unidimensionalExport(workspace.query.parameters,$scope.rptUUID).then(function(data){
                //         var file = new Blob([ data ], {
                //             type : 'application/vnd.ms-excel;charset=utf-8;'
                //         });
                //         //trick to download store a file having its URL
                //         var fileURL = URL.createObjectURL(file);
                //         var a         = document.createElement('a');
                //         a.href        = fileURL; 
                //         a.target      = '_blank';
                //         a.download    = filename+"xls";
                //         document.body.appendChild(a);
                //         a.click();
                // })
                $http({
                    url : api_statistic.unidimensionalExport($scope.rptUUID).getRequestedUrl(),
                    method : 'POST',
                    data : workspace.query.parameters,
                    headers : {
                        //'Content-type' : 'application/xls',
                        'Accept': '*/*'
                    },
                    responseType : 'arraybuffer'
                }).success(function(data, status, headers, config) {
                        var file = new Blob([ data ], {
                            type : 'application/vnd.ms-excel'
                        });
                        //trick to download store a file having its URL
                        var fileURL = URL.createObjectURL(file);
                        var a         = document.createElement('a');
                        a.href        = fileURL; 
                        a.target      = '_blank';
                        a.download    = filename+"xls";
                        document.body.appendChild(a);
                        a.click();
                }).error(function(data, status, headers, config) {
                    console.log(data);
                });
		
            }else{
			$http({
                    url : api_report.exportData('flat', uuid, encodeURIComponent(filename)).getRequestedUrl(),
                    method : 'POST',
                    data : workspace.query,
                    headers : {
                        //'Content-type' : 'application/xls',
                        'Accept': 'application/vnd.ms-excel',
                        'X-Auth-Token' : $cookieStore.get('Auth-Token')||null
                    },
                    responseType : 'arraybuffer'
                }).success(function(data, status, headers, config) {
                        var file = new Blob([ data ], {
                            type : 'application/vnd.ms-excel'
                        });
                        //trick to download store a file having its URL
                        var fileURL = URL.createObjectURL(file);
                        var a         = document.createElement('a');
                        a.href        = fileURL; 
                        a.target      = '_blank';
                        a.download    = filename+"xls";
                        document.body.appendChild(a);
                        a.click();
                }).error(function(data, status, headers, config) {
                    console.log(data);
                });
            }
		}



		/*
		if(workspace.query.name!=undefined){
			var filename = name.substring(name.lastIndexOf('/')+1).slice(0, -5);
			window.location=api_report.exportData('flat', encodeURIComponent(filename)).getRequestedUrl();
		}*/


			// if(workspace.query.name!=undefined){
			// 	var filename = name.substring(name.lastIndexOf('/')+1).slice(0, -5);
			// 	//var win = window.open('_blank');
			// 	downFile(api_report.exportData('flat', encodeURIComponent(filename)).getRequestedUrl(), function(blob){
			// 		var url = URL.createObjectURL(blob);
			// 		window.location = url;
			// 	});
			// }
    }

    function downFile(url, success){
    	var xhr = new XMLHttpRequest();
    	xhr.open('GET', url, true);
    	xhr.setRequestHeader("X-Auth-Token", $cookieStore.get('Auth-Token'))
    	xhr.responseType = "blob";
    	xhr.onreadystatechange = function(){
    		if(xhr.readyState == 4){
    			if(success) success(xhr.response);
    		}
    	}
    }

    $scope.rheaders = [];
    $scope.rRows = [];


    function executeQuery(mdxquery){
    	api_report.execute(mdxquery).then(function(data){
    		$scope.rheaders = [];
    		$scope.rRows = [];
        	var reportData = Restangular.stripRestangular(data);
        	//console.log(reportData);
        	var tableContent = render(reportData);
        	//console.log(tableContent);
        	//console.log($scope.rheaders);
        }) 
    }
        

    function render(data){
    	return internalRenderTable(data);
    }



    function internalRenderTable(allData){
    	var tableContent = "";
    	var rowContent = "";
    	var data = allData.cellset;

    	var table = data ? data : [];
    	var colSpan;
    	var colValue;
    	var isHeaderLowestLvl;
    	var isBody = false;
    	var firstColumn;
    	var isLastColumn, isLastRow;
    	var nextHeader;
    	var processedRowHeader = false;
    	var lowestRowLvl = 0;
    	var rowGroups = [];
    	var batchSize = null;
    	var batchStarted = false;
    	var isColHeader = false, isColHeaderDone = false;
    	var resultRows = [];
	    var wrapContent = true;

	    var colHeaders = [];
	    var rowHeaders = [];
	    var rowDatas = [];
	    var allDatas = [];
	    // if (options) {
	    //     batchSize = options.hasOwnProperty('batchSize') ? options.batchSize : null;
	    //     wrapContent = options.hasOwnProperty('wrapContent') ? options.wrapContent : true;
	    // }
	    var totalsLists = {};
	    totalsLists[COLUMNS] = allData.rowTotalsLists;
	    totalsLists[ROWS] = allData.colTotalsLists;
    
	    var scanSums = {};
	    var scanIndexes = {};
    
	    var dirs = [ROWS, COLUMNS];
	    
	    for (var i = 0; i < dirs.length; i++) {
	        scanSums[dirs[i]] = new Array();
	        scanIndexes[dirs[i]] = new Array();
	    }
    	if (totalsLists[COLUMNS])
	        for (var i = 0; i < totalsLists[COLUMNS].length; i++) {
	            scanIndexes[COLUMNS][i] = 0;
	            scanSums[COLUMNS][i] = totalsLists[COLUMNS][i][scanIndexes[COLUMNS][i]].width;
	        }


    		for (var row = 0, rowLen = table.length; row < rowLen; row++) {
		        var rowShifted = row - allData.topOffset;
		        colSpan = 1;
		        colValue = "";
		        isHeaderLowestLvl = false;
		        isLastColumn = false;
		        isLastRow = false;
		        isColHeader = false;
		        var headerSame = false;

		        if (totalsLists[ROWS])
		            for (var i = 0; i < totalsLists[ROWS].length; i++) {
		                scanIndexes[ROWS][i] = 0;
		                scanSums[ROWS][i] = totalsLists[ROWS][i][scanIndexes[ROWS][i]].width;
		            }
			        rowContent = "<tr>";
			        if ( row === 0) {
			            rowContent = "<thead>" + rowContent;
			        }
			        for (var col = 0, colLen = table[row].length; col < colLen; col++) {
			            var colShifted = col - allData.leftOffset;
			            var header = data[row][col];
			            if (header.type === "COLUMN_HEADER") {
			                isColHeader = true;
			            }

			            // If the cell is a column header and is null (top left of table)
			            if (header.type === "COLUMN_HEADER" && header.value === "null" && (firstColumn == null || col < firstColumn)) {
			                rowContent += '<th class="all_null">&nbsp;</th>';
			                var headerObject = { thclass: 'all_null', value: '\u00A0/\u00A0'};
			                colHeaders.push(headerObject);
			            } // If the cell is a column header and isn't null (column header of table)
			            else if (header.type === "COLUMN_HEADER") {
			                if (firstColumn == null) {
			                    firstColumn = col;
			                }
			                if (table[row].length == col+1)
			                    isLastColumn = true;
			                else
			                    nextHeader = data[row][col+1];


			                if (isLastColumn) {
			                    // Last column in a row...
			                    if (header.value == "null") {
			                        rowContent += '<th class="col_null">&nbsp;</th>';
			                        var headerObject = { thclass: 'all_null', value: '\u00A0/\u00A0'};
			                		colHeaders.push(headerObject);
			                    } else {
			                        if (totalsLists[ROWS])
			                            colSpan = totalsLists[ROWS][row + 1][scanIndexes[ROWS][row + 1]].span;
			                        rowContent += '<th class="col" style="text-align: center;" colspan="' + colSpan + '" title="' + header.value + '">'
			                            + (wrapContent ? '<div rel="' + row + ":" + col +'">' + header.value + '</div>' : header.value)
			                            + '</th>';    
			                        var headerObject = { thclass: 'col', colspan:''+colSpan+'', title:header.value};
			                        if(wrapContent){
			                        	headerObject.value = { rel: row+":"+col, value: header.value };
			                        }else{
			                        	headerObject.value = header.value;
			                        }
			                		colHeaders.push(headerObject);
			                    }
			                    
			                } else {
			                    // All the rest...
			                    var groupChange = (col > 1 && row > 1 && !isHeaderLowestLvl && col > firstColumn) ?
			                        data[row-1][col+1].value != data[row-1][col].value || data[row-1][col+1].properties.uniquename != data[row-1][col].properties.uniquename
			                        : false;

			                    var maxColspan = colSpan > 999 ? true : false;
			                    if (header.value != nextHeader.value || nextParentsDiffer(data, row, col) || isHeaderLowestLvl || groupChange || maxColspan) {
			                        if (header.value == "null") {
			                            rowContent += '<th class="col_null" colspan="' + colSpan + '">&nbsp;</th>';
			                            var headerObject = { thclass: 'col_null', colspan:colSpan, value:"&nbsp;"};
				                        colHeaders.push(headerObject);
			                        } else {
			                            if (totalsLists[ROWS])
			                                colSpan = totalsLists[ROWS][row + 1][scanIndexes[ROWS][row + 1]].span;
			                            rowContent += '<th class="col" style="text-align: center;" colspan="' + (colSpan == 0 ? 1 : colSpan) + '" title="' + header.value + '">'
			                            + (wrapContent ? '<div rel="' + row + ":" + col +'">' + header.value + '</div>' : header.value)
			                            + '</th>';

			                            var headerObject = { thclass: 'col', colspan:(colSpan == 0 ? 1 : colSpan), title:header.value};
				                        if(wrapContent){
				                        	headerObject.value = { rel: row+":"+col, value: header.value };
				                        }else{
				                        	headerObject.value = header.value;
				                        }
				                		colHeaders.push(headerObject); 
			                        }
			                        colSpan = 1;
			                    } else {
			                        colSpan++;
			                    }
			                }



			                if (totalsLists[ROWS])
			                    rowContent += genTotalHeaderCells(col - allData.leftOffset + 1, row + 1, scanSums[ROWS], scanIndexes[ROWS], totalsLists[ROWS], wrapContent);
				            	//TODO
				            } // If the cell is a row header and is null (grouped row header)
				            else if (header.type === "ROW_HEADER" && header.value === "null") {
				                rowContent += '<th class="row_null">&nbsp;</th>';
				                var headerObject = { thclass: 'row_null', value:header.value};
				                colHeaders.push();
				            } // If the cell is a row header and isn't null (last row header)
				            else if (header.type === "ROW_HEADER") {
				                if (lowestRowLvl == col)
				                    isHeaderLowestLvl = true;
				                else
				                    nextHeader = data[row][col+1];

				                var previousRow = data[row - 1];
				                var headerObject = {};
				                var same = !headerSame && !isHeaderLowestLvl && (col == 0 || !topParentsDiffer(data, row, col)) && header.value === previousRow[col].value;
				                headerSame = !same;
				                var value = (same ? "<div>&nbsp;</div>" : '<div rel="' + row + ":" + col +'">' + header.value + '</div>');
				                if(same){
				                	headerObject.value = {
				                		value:'\u00A0/\u00A0'
				                	}
				                }else{
				                	headerObject.value = {
				                		value:header.value,
				                		rel:row + ":" + col
				                	}
				                }
				                if (!wrapContent) {
				                    value = (same ? "&nbsp;" : header.value );
				                    if(same){
				                    	headerObject.value='\u00A0/\u00A0';
				                    }else{
				                    	headerObject.value=header.value;
				                    }
				                    
				                }
				                var tipsy = "";
	                
				                var cssclass = (same ? "row_null" : "row");
				                var colspan = 0;

				                if (!isHeaderLowestLvl && (typeof nextHeader == "undefined" || nextHeader.value === "null")) {
				                    colspan = 1;
				                    var group = header.properties.dimension;
				                    var level = header.properties.level;
				                    var groupWidth = (group in rowGroups ? rowGroups[group].length - rowGroups[group].indexOf(level) : 1);
				                    for (var k = col + 1; colspan < groupWidth && k <= (lowestRowLvl+1) && data[row][k] !== "null"; k++) {
				                        colspan = k - col;
				                    }
				                    col = col + colspan -1;
				                }
				                rowContent += '<th class="' + cssclass + '" ' + (colspan > 0 ? ' colspan="' + colspan + '"' : "") + tipsy + '>' + value + '</th>';
				                headerObject.thclass=cssclass;
				                if(colspan>0){
				                	console.log("colspan:"+colspan);
				                	headerObject.colspan = colspan;
				                }
				                console.log("-----");
				                console.log(headerObject);
				                rowDatas.push(headerObject);
				            }
				            else if (header.type === "ROW_HEADER_HEADER") {
				                rowContent += '<th class="row_header">' + (wrapContent ? '<div>' + header.value + '</div>' : header.value) + '</th>';
				                var headerObject = { thclass: 'row_header', value:header.value};
				                if(wrapContent){
				                	headerObject.value = {
				                		value:header.value
				                	}
				                }else{
				                	headerObject.value=header.value;
				                }
				                
				                colHeaders.push(headerObject);

				                isHeaderLowestLvl = true;
				                processedRowHeader = true;
				                lowestRowLvl = col;
				                if (header.properties.hasOwnProperty("dimension")) {
				                    var group = header.properties.dimension;
				                    if (!(group in rowGroups)) {
				                        rowGroups[group] = [];
				                    }
				                    rowGroups[group].push(header.properties.level);
				                }
				            } // If the cell is a normal data cell
				            else if (header.type === "DATA_CELL") {
				                batchStarted = true;
				                var color = "";
				                var val = header.value;
				                var arrow = "";
				                var rowEntity = {};
				                if (header.properties){
					                if (header.properties.hasOwnProperty('image')) {
					                    var img_height = header.properties.hasOwnProperty('image_height') ? " height='" + header.properties.image_height + "'" : "";
					                    var img_width = header.properties.hasOwnProperty('image_width') ? " width='" + header.properties.image_width + "'" : "";
					                    val = "<img " + img_height + " " + img_width + " style='padding-left: 5px' src='" + header.properties.image + "' border='0'>";
					                }
	
					                if (header.properties.hasOwnProperty('style')) {
					                    color = " style='background-color: " + header.properties.style + "' ";
					                    rowEntity.rowStyle={'background-color':header.properties.style};
					                }
					                if (header.properties.hasOwnProperty('link')) {
					                    val = "<a target='__blank' href='" + header.properties.link + "'>" + val + "</a>";
					                    //rowEntity.value=
					                }
					                if (header.properties.hasOwnProperty('arrow')) {
					                    arrow = "<img height='10' width='10' style='padding-left: 5px' src='./images/arrow-" + header.properties.arrow + ".gif' border='0'>";
					                	//rowEntity.arrow=
					                }
					              }else{
					              	header.properties = {};
					              }

				                rowContent += '<td class="data" ' + color + '>'
				                        + (wrapContent ? '<div class="datadiv" alt="' + header.properties.raw + '" rel="' + header.properties.position + '">' : "")
				                        + val + arrow 
				                        + (wrapContent ? '</div>' : '') + '</td>';
				                if(wrapContent){
				                	rowEntity.value={
				                		alt:header.properties.raw,
				                		rel:header.properties.position,
				                		value:val
				                	}
				                }else{
				                	rowEntity.value=val;
				                }
				                rowDatas.push(rowEntity);


				                if (totalsLists[ROWS])
				                    rowContent += genTotalDataCells(colShifted + 1, rowShifted, scanSums[ROWS], scanIndexes[ROWS], totalsLists, wrapContent);
				            }
	        			}
				        rowContent += "</tr>";
                        if(colHeaders.length!=0&&colHeaders[0].value.value=="(All)"){colHeaders=colHeaders.splice(1,6)}
				        $scope.rheaders.push(colHeaders);
                        // $scope.rheaders=$scope.rheaders[0].splice(1,1)
				        colHeaders = [];
				        if(rowDatas.length>1){
                            if(rowDatas.length!=0&&rowDatas[0].value.value=="所有状态"){rowDatas[0].colspan=""}
                            if(rowDatas.length!=0&&rowDatas[0].thclass=="row_null"){rowDatas=rowDatas.splice(1,6)}
				        	$scope.rRows.push(rowDatas);
				        	rowDatas = [];
				        }
                        console.log($scope.rRows)
				        var totals = "";
				        if (totalsLists[COLUMNS] && rowShifted >= 0) {
				            totals += genTotalHeaderRowCells(rowShifted + 1, scanSums, scanIndexes, totalsLists, wrapContent);
				        }
	        			if (batchStarted && batchSize) {
			                if (row <= batchSize) {
			                    if (!isColHeader && !isColHeaderDone) {
			                        tableContent += "</thead><tbody>";
			                        isColHeaderDone = true;
			                    }
			                    tableContent += rowContent;
			                    if (totals.length > 0) {
			                        tableContent += totals;
			                    }
			                    
			                } else {
			                    resultRows.push(rowContent);
			                    if (totals.length > 0) {
			                        resultRows.push(totals);
			                    }
			                        
			                }
				        } else {
				            if (!isColHeader && !isColHeaderDone) {
				                tableContent += "</thead><tbody>";
				                isColHeaderDone = true;
				            }
				            tableContent += rowContent;
				            if (totals.length > 0) { 
				                tableContent += totals;
				            }
				        }
	    			}
	    			if($scope.reportName=="事件详细资料"){
	    				var hmainCol=53*$scope.rRows.length;
    				    $scope.allheight=hmainCol+160;
	    			// }else if($scope.reportName=="事件解决率统计"){
	    			// 	var hmainCol=35*($scope.rRows.length+2);
    				//     $scope.allheight=hmainCol+570;
    			    }else if($scope.reportName=="事件工作回顾"||$scope.reportName=="事件解决率统计"){
	    				var hmainCol=35*($scope.rRows.length);
    				    $scope.allheight=hmainCol+140;
	    			}else{var hmainCol=35*$scope.rRows.length;
    				    $scope.allheight=hmainCol+570;
    			    }
	    			
	    // if (options) {
	    //     options['batchResult'] = resultRows;
	    //     options['hasBatchResult'] = resultRows.length > 0;
	    // }
	    return "<table>" + tableContent + "</tbody></table>";
    }
    // $scope.rheaders=$scope.rheaders.splice(1,1)
    function nextParentsDiffer(data, row, col) {
	    while (row-- > 0) {
	        if (data[row][col].properties.uniquename != data[row][col + 1].properties.uniquename)
	            return true;
	    }
	    return false;
	}

	// $scope.chartType="doughnut";
	// //chart view
	// $scope.chartData = [
	//   { value : 50, color : "#F7464A" },
	//   { value : 90, color : "#E2EAE9" },
	//   { value : 75, color : "#D4CCC5" },
	//   { value : 30, color : "#949FB1"}
	// ];

	// $scope.chartOptions =  {
	//   // Chart.js options can go here.
	// };

	$scope.onChartClick = function (event) {
	  console.log(event);
	};

	var tmpHSV=undefined;
	function randomHSV(hsv){
		if(angular.isUndefined(hsv)){
			return {
				h:0,
				s:0.75,
				v:0.8
			};
		}else{
			return {
				h:hsv.h+51.5,
				s:0.75,
				v:0.8
			}
		}
	}

	function HSVToRGB(h,s,v){
        var i;
        var f, p, q, t;
        var r,g,b;
        if( s == 0 ) {
            v = Math.floor(v*255);
            return {
                r:v,
                g:v,
                b:v
            };
        }
        h /= 60;
        i = Math.floor( h );
        f = h - i;
        p = v * ( 1 - s );
        q = v * ( 1 - s * f );
        t = v * ( 1 - s * ( 1 - f ) );
        switch( i ) {
            case 0:r = v;g = t;b = p;break;
            case 1:r = q;g = v;b = p; break;
            case 2: r = p;g = v;b = t;break;
            case 3:r = p;g = q;b = v;break;
            case 4:r = t;g = p;b = v;break;
            default:r = v;g = p;b = q;break;
        }
        return {
            r:r*255,
            g:g*255,
            b:b*255
        };
    };

    function colorToHex(color) {
	    var red = color.r;
	    var green = color.g;
	    var blue = color.b;
	    
	    var rgb = blue | (green << 8) | (red << 16);
	    return '#' + rgb.toString(16);
	};


}]);